use serde::Deserialize;
use std::fs;
use std::error::Error;
use rand;

#[derive(Debug, Deserialize)]
pub struct Config {
    pub connection: ConnectionConfig,
    pub topics: TopicsConfig,
    pub message: MessageConfig,
    pub ui: UiConfig,
}

#[derive(Debug, Deserialize)]
pub struct ConnectionConfig {
    pub broker_address: String,
    pub port: String,
    pub client_id: String,
}

#[derive(Debug, Deserialize)]
pub struct TopicsConfig {
    pub publish_topic: String,
    pub subscribe_topic: String,
}

#[derive(Debug, Deserialize)]
pub struct MessageConfig {
    pub default_payload: String,
}

#[derive(Debug, Deserialize)]
pub struct UiConfig {
    pub dark_mode: bool,
    pub window_width: f32,
    pub window_height: f32,
    pub min_window_width: f32,
    pub min_window_height: f32,
}

impl Config {
    pub fn load() -> Result<Self, Box<dyn Error>> {
        let config_str = fs::read_to_string("config/config.toml")?;
        let mut config: Config = toml::from_str(&config_str)?;
        
        // Replace {random} in client_id with a random number
        if config.connection.client_id.contains("{random}") {
            config.connection.client_id = config.connection.client_id.replace("{random}", &rand::random::<u32>().to_string());
        }
        
        Ok(config)
    }

    pub fn default() -> Self {
        Config {
            connection: ConnectionConfig {
                broker_address: "localhost".to_string(),
                port: "1883".to_string(),
                client_id: format!("mqtt-client-{}", rand::random::<u32>()),
            },
            topics: TopicsConfig {
                publish_topic: "test/topic".to_string(),
                subscribe_topic: "test/topic".to_string(),
            },
            message: MessageConfig {
                default_payload: r#"{
    "message": "Hello MQTT",
    "timestamp": 1234567890
}"#.to_string(),
            },
            ui: UiConfig {
                dark_mode: true,
                window_width: 1000.0,
                window_height: 700.0,
                min_window_width: 800.0,
                min_window_height: 600.0,
            },
        }
    }
} 